<template>
  <div>
    <el-card shadow="always" :body-style="{padding:'20px'}">
      <!--      表头-->
      <template #header>
        <el-button v-has="'btn.Trademark.add'" @click="addTradeMarkItem" type="primary" icon="ele-Plus">添加</el-button>
      </template>
      <!--      添加/修改的弹窗-->
      <el-dialog
          v-model="dialogVisible"
          :title="formData.id?'修改品牌':'添加品牌'"
          width="30%"
      >
        <el-form
            label-width="120px"
            class="demo-ruleForm"
            status-icon
            ref="ruleFormRef"
            :model="formData"
            :rules="rules"
        >
          <el-form-item label="品牌名称" prop="tmName" style="width: 80%">
            <el-input v-model="formData.tmName"/>
          </el-form-item>

          <el-form-item label="品牌LOGO" prop="logoUrl" style="width: 80%">
            <el-upload
                class="avatar-uploader"
                action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
              <img v-if="formData.logoUrl" :src="formData.logoUrl" class="avatar"/>
              <el-icon v-else class="avatar-uploader-icon">
                <ele-Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="addOrUpdate">
                确定
              </el-button>
            </span>
        </template>
      </el-dialog>
      <!--      表单-->
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80"/>
        <el-table-column prop="tmName" label="品牌名称"/>
        <el-table-column label="品牌Logo">
          <!-- 表格作用域插槽的作用域数据row代表当前行完整数据 $index代表当前数据的下标 -->
          <template v-slot="{row}">
            <div>
              <el-image :preview-src-list="[row.logoUrl]" :preview-teleported="true"
                        style="width:100px"
                        :src="row.logoUrl" fit="fill"
                        :lazy="true"></el-image>
            </div>
          </template>
        </el-table-column>
        >
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button type="warning" size="small" icon="ele-Edit"
                       v-has="'btn.Trademark.update'" @click="updateTrademarkItem(row)"
            >修改
            </el-button
            >
            <el-popconfirm title="Are you 确定删除我?" @confirm="confirmEvent(row.id)"
                           @cancel="cancelEvent">
              <template #reference>
                <el-button type="danger" size="small" icon="ele-Delete"
                           v-has="'btn.Trademark.remove'" >删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页器-->
      <el-pagination
          :background="true"
          v-model:page-size="limit"
          v-model:current-page="currentPage"
          :page-count="pageCount"
          :page-sizes="[10, 20, 30, 40]"
          :pager-count="5"
          layout="sizes, prev, pager, next, jumper"
      />
    </el-card>
  </div>
</template>

<script lang="ts">
import {defineComponent} from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import {onMounted, reactive, ref, watch} from "vue";
import useTrademarkStore from "@/stores/trademark";
import type {TrademarkItemType} from "@/api/trademark";
import {ElMessage, type FormInstance, type FormRules, type UploadProps} from "element-plus";
import {reqDeleteTrademarkItemAsync, reqPostTrademarkItemAsync, reqPutTrademarkItemAsync} from "@/api/trademark";

// 获取store对象
const trademarkStore = useTrademarkStore()

// 初始品牌管理数据
const tableData = ref<TrademarkItemType[]>([])

// page-size 每页显示的条目个数
const limit = ref(10)

// 当前页数 初始数据
const currentPage = ref(1)

// 总页数 初始数据
const pageCount = ref(0)

// 获取品牌管理数据
const getTrademarkList = async () => {
  try {
    await trademarkStore.getTrademarkList(currentPage.value, limit.value);
    tableData.value = trademarkStore.trademarkList
    pageCount.value = trademarkStore.pages
  } catch (e) {
    ElMessage.error("熏染失败")
  }
}
// 挂载时获取数据 重新更新页面
onMounted(() => {
  getTrademarkList()
})
// 当页码发生改变时 更新页面
watch([currentPage, limit], () => {
  getTrademarkList()
})


// 控制 添加/修改的弹窗 是否隐藏
const dialogVisible = ref(false)


// 收集表单数据
const formData = ref<TrademarkItemType>({
  tmName: '',
  logoUrl: ''
})

// 失焦时表单的单独校验
const rules = reactive<FormRules>({
  tmName: [
    {required: true, message: '品牌名不能为空', trigger: 'blur'},
  ],
  logoUrl: [
    {required: true, message: '图片不能为空', trigger: 'blur'},
  ]
})

// 上传成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  // base 图片解析 64位
  formData.value.logoUrl = response.data
}

// 图片的校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('格式只能为jpg!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像不能大于2MB!')
    return false
  }
  return true
}

// 添加功能
const addTradeMarkItem = () => {
  // 开启弹窗
  dialogVisible.value = true;
  // 清空表单(点修改再点添加form有数据)
  formData.value = {
    tmName: '',
    logoUrl: ''
  }

  // 每次检验的时候 清除前一个校验
  ruleFormRef.value?.resetFields()
}

// 修改功能
const updateTrademarkItem = (row: TrademarkItemType) => {
  // 开启弹窗
  dialogVisible.value = true;
  // 更新表单数据(对象不能直接复制 不然会互相影响 所以 拷贝一下)
  formData.value = {...row}

  // 每次检验的时候 清除前一个校验
  ruleFormRef.value?.resetFields()
}

// 获取from表单这个组件
const ruleFormRef = ref<FormInstance>()

//新增或者修改品牌的回调函数
const addOrUpdate = async () => {
  // 提交时 表单的整体校验
  const re = await ruleFormRef.value?.validate(() => {
  });  // 这里加函数 就为了处理警告中的没有处理报错
  if (!re) return

  try {
    //先根据trademarkData中的id判断当前是更新还是新增
    if (formData.value.id) {
      await reqPutTrademarkItemAsync(formData.value);
      ElMessage.success("更新成功");
    } else {
      await reqPostTrademarkItemAsync(formData.value);
      ElMessage.success("新增成功");
    }
  } catch (e: any) {
    ElMessage.error(e.message);
  }
  //关闭弹窗
  dialogVisible.value = false;
  // 重新获取数据
  await getTrademarkList();
};

// 删除功能
const confirmEvent = async (id: number) => {  // 确定
  try {
    await reqDeleteTrademarkItemAsync(id)
    // 刷新页面
    await getTrademarkList()
    ElMessage.success('删除成功')
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}
const cancelEvent = () => {   // 取消
  ElMessage.error('你说不删就不删？')
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>